package com.yjz.log.print.view;

import android.app.Activity;
import android.view.LayoutInflater;
import android.widget.FrameLayout;

import androidx.annotation.NonNull;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.yjz.log.print.ILogPrinter;

/**
 * 作用 : 在view中打印日志
 * 作者 : yjz
 * 时间 : 2024/9/14 15:49
 */
public class ViewPrinter implements ILogPrinter {

    private RecyclerView recyclerView;
    private LogViewAdapter adapter;
    private ViewPrinterProvider viewProvider;

    public ViewPrinter(Activity activity) {
        FrameLayout rootView = activity.findViewById(android.R.id.content);
        recyclerView = new RecyclerView(activity);
        adapter = new LogViewAdapter(LayoutInflater.from(recyclerView.getContext()));
        LinearLayoutManager layoutManager = new LinearLayoutManager(recyclerView.getContext());
        recyclerView.setLayoutManager(layoutManager);
        recyclerView.setAdapter(adapter);
        viewProvider = new ViewPrinterProvider(rootView, recyclerView);
    }

    @Override
    public void print(int level, String tag, @NonNull String printString) {
        // 将log展示添加到recycleView
        adapter.addItem(new LogModel(System.currentTimeMillis(), level, tag, printString));
        // 滚动到对应的位置
        recyclerView.smoothScrollToPosition(adapter.getItemCount() - 1);
    }

    @NonNull
    public ViewPrinterProvider getViewProvider() {
        return viewProvider;
    }
}
